//我们强烈推荐你在代码最外层把需要用到的模块先加载
layui.use(['layer', 'element'], function () {
    let layer = layui.layer;
    let element = layui.element;
    //登陆按钮
    $('.login').on('click', '.submit', function () {
        login();
    })

    //取消按钮
    $('.login').on('click', '.cancel', function () {
        ipcRenderer.send('send-cancel', '');
    })

    checkVersion();

    function login() {
        let privateKey = $("#privateKey").val();
        if (!judgeFormInput(privateKey)) {
            return;
        }
        //获取登录接口url
        let apiKeyLoginUrl = apiArr[0];
        let index = layer.msg("<div class='tip-content'>验证私钥中,请等待...</div>", {
            icon: 16,
            time: 0
        });
        $.ajax({
            url: apiKeyLoginUrl,
            data: 'privateKey=' + $('#privateKey').val(),
            dataType: 'json',
            type: 'POST',
            //timeout: 8000,
            success: function (data) {
                layer.close(index);
                if (data.result) {
                    ipcRenderer.send('login-success', data.data);
                } else {
                    layer.alert('私钥不存在！', {
                        title: '提示'
                    });
                }
            },
            error: function (e) {
                layer.close(index);
                layer.alert('服务器连接失败，请联系管理员！', {
                    title: '提示'
                });
            }
        });

    }

    function judgeFormInput(privateKey) {
        if (!privateKey) {
            layer.alert('请输入密钥！', {
                title: '提示'
            });
            return false;
        }
        return true;
    }
    //更新提示测试
    /*  var n = 0,
         timer = setInterval(function () {
             n = n + Math.random() * 10 | 0;
             if (n > 100) {
                 n = 100;
                 clearInterval(timer);
                 layer.close(index);
                 
             }
             if (!index) {
                 index = layer.msg('<div>更新进度：<span id="updatePrecent"></sapn>%</div>', {
                     icon: 16,
                     shade: 0.4,
                     time: 0
                 });
             } else {
                 $("#updatePrecent").text(n);
             }
         }, 300 + Math.random() * 1000); */

    function checkVersion() {
        ipcRenderer.on('checkVersion', function () {
            let obj = {
                type: "get",
                timeout: 4000,
                url: packageObj.updateRepo + "/" + packageObj.updateFile + "?r=" + Math.random(),
            }
            let arr = null;
            let vConfigfilepath = null;
            ajaxPromise(obj).then((obj) => {
                let data = obj.data;
                arr = data.split("###");
                vConfigfilepath = path.join(`${__dirname}`, '..', '..', '..', 'version.ini');
                return Q.nfcall(fs.readFile, vConfigfilepath, 'utf-8');
            }).then((curVersion) => {
                let curVersionNum = Number(curVersion.replace(/\./g, ''));
                let newVersionNum = Number(arr[0].trim().replace(/\./g, ''));
                if (curVersionNum < newVersionNum) {
                    layer.open({
                        type: 1,
                        area: ['300px'],
                        content: "<div class='tip-content'>系统检测到新版本，是否更新？</div>",
                        btn: ['更新', '取消'], //可以无限个按钮
                        yes: function (index, layero) {
                            //按钮【按钮一】的回调
                            layer.close(layer.index);
                            layer.msg("<div class='tip-content'>系统升级中,请等待...</div>", {
                                icon: 16,
                                time: 0
                            });
                            //跟新数据库操作,将版本放入数组中
                            var versionArr = [];
                            var sqlArr = [];
                            for (var i = 1; i < arr.length; i++) {
                                var temp = arr[i].trim().split("@@@");
                                versionArr.push(temp[0].trim());
                                sqlArr.push(temp[1].trim());
                            }
                            //比较当前版本和服务器最新版本，执行服务器最新版本大于当前版本的sql语句
                            var postIndex = 0;
                            for (var pi = 0; pi < versionArr.length; pi++) {
                                if (curVersionNum < Number(versionArr[pi].replace(/\./g, ''))) {
                                    break;
                                }
                                postIndex++;
                            }
                            var serializeSql = null;
                            for (var sq = postIndex; sq < sqlArr.length; sq++) {
                                serializeSql = (serializeSql == null ? sqlArr[sq] : serializeSql + ";" + sqlArr[sq]);
                            }
                            if (serializeSql) {
                                db.serializeSql(serializeSql, function () {});
                            }
                            //下载zip文件
                            ipcRenderer.on('unzipComplete', (event, arg) => {
                                var appflag = true;
                                while (appflag) {
                                    try {
                                        fs.unlinkSync(path.join(`${__dirname}`, '..', '..', '..', 'app.zip'));
                                        appflag = false;
                                    } catch (e) {
                                        console.log("还未解压完成", e);
                                    }
                                }
                                fs.writeFile(vConfigfilepath, arr[0], (err) => {
                                    if (err) log.error(err);
                                    log.info('版本更新成功');
                                });
                                layer.close(layer.index);
                                layer.alert("升级成功,请重启农资进销存管理系统软件", {
                                    title: "升级成功",
                                    closeBtn: 0
                                }, function (ind) {
                                    layer.close(ind);
                                    ipcRenderer.send('closed-message', "");
                                });
                            });
                            ipcRenderer.send('download-zip', packageObj.updateRepo + "/" + arr[0].trim() + ".zip");
                        },
                        btn2: function (index, layero) {
                            //按钮【按钮二】的回调
                            //return false 开启该代码可禁止点击该按钮关闭

                        }
                    });
                }
            }).catch((e) => {
                console.log('连接超时！');
            })
        });
        ipcRenderer.send('readyCheckUpdate');
    }

});
ipcRenderer.on('checkUpdate', function () {
    alert();
})